﻿using System;
using System.Linq;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using System.Collections.Generic;
using ComApp.Model;
using ComApp;

namespace AndroidApp
{
    [Activity(Theme = "@android:style/Theme.NoTitleBar")]
    public class UploadedView : BaseActivity
    {
        private string TempCode;
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            this.SetChildContentView(Resource.Layout.UploadedView);
            AppUnity.Instance.LogService.Log("Open UploadedView成功");
            this.TempCode = Intent.GetStringExtra("TempCode");



            var closeUploaded = FindViewById<Button>(Resource.Id.closeUploaded);
            closeUploaded.Click += (s, e) =>
            {
                this.Finish();
            };


            var downloadUrlTextView = FindViewById<TextView>(Resource.Id.downloadUrl);
            downloadUrlTextView.Click += (s, e) =>
            {
                var popMenu = new PopMenu(this, new List<string>() { "复制", "下载" });
                popMenu.listView.ItemClick += (sender2, e2) =>
                {
                    popMenu.Dismiss();
                    var textView = e2.View.FindViewById<TextView>(Resource.Id.textview);
                    var selectedMenu = textView.Text;
                    if (selectedMenu == "复制")
                    {
                        var clipboard = (ClipboardManager)this.GetSystemService(Context.ClipboardService);
                        clipboard.Text = downloadUrlTextView.Text;
                    }
                    else if (selectedMenu == "下载")
                    {
                        Intent intent = new Intent(this, typeof(DownloadView));
                        intent.PutExtra("TempCode", this.TempCode);
                        intent.SetFlags(ActivityFlags.ReorderToFront);
                        StartActivity(intent);
                    }
                };
                popMenu.ShowAsDropDown(downloadUrlTextView);
            };


        }

        private void downloadUrlTextView_Click(object sender, EventArgs e)
        {
            var downloadUrlTextView = FindViewById<TextView>(Resource.Id.downloadUrl);
            PopupMenu menu = new PopupMenu(this, downloadUrlTextView);
            menu.Inflate(Resource.Menu.CopyMenu);

            menu.MenuItemClick += (s1, arg1) =>
            {
                var selectedMenu = arg1.Item.TitleFormatted.ToString();
                arg1.Handled = true;
                menu.Dismiss();
                menu.Dispose();
                if (selectedMenu == "复制")
                {
                    var clipboard = (ClipboardManager)this.GetSystemService(Context.ClipboardService);
                    clipboard.Text = downloadUrlTextView.Text;
                }
                else if (selectedMenu == "转到下载页面")
                {
                    Intent intent = new Intent(this, typeof(DownloadView));
                    intent.PutExtra("TempCode", this.TempCode);
                    intent.SetFlags(ActivityFlags.ReorderToFront);
                    StartActivity(intent);
                }
            };

            menu.DismissEvent += (s2, arg2) =>
            {
                //Toast.MakeText(this,"dismissed", ToastLength.Short).Show();
            };
            menu.Show();
        }


        /// <summary>
        /// 从任务栏移走，会CloseBeforeExit，但不会提示
        /// 回退到桌面会提示退出，相当于应用退出 
        /// 隐藏到后台重新激活（从任务栏或桌面），会刷新，但没有退出过
        /// 还需要测试打开另一个Activity的情况
        /// </summary>
        protected override bool CloseBeforeExit()
        {

            //Widget.HttpImageView.DeleteCacheFileAllAsync().ContinueWith(t =>
            //{
            //    if (!t.IsFaulted && !t.IsCanceled)
            //    {
            //        RunOnUiThread(() =>
            //        {
            //            Toast.MakeText(this, "删除成功完成", ToastLength.Long).Show();
            //        });

            //    }
            //});

            return true;
        }

        private void RefreshImg()
        {
            var metrics = Resources.DisplayMetrics;
            var url = string.Format("http://{0}/{1}",AppUnity.Instance.ServerDeploy.WebServerHostName,TempCode);
            var downloadUrlTextView = FindViewById<TextView>(Resource.Id.downloadUrl);
            downloadUrlTextView.Text = url;

            AppUnity.Instance.LogService.Log(string.Format("正在生成二维码{0}", url));
            var w = metrics.WidthPixels > metrics.HeightPixels ? metrics.HeightPixels : metrics.WidthPixels;
            var bitmap = BarCode2D.Instance.Create(url, w);
            var imageView = FindViewById<ImageView>(Resource.Id.image2dBar);
            imageView.SetImageBitmap(bitmap);
        }

        //private int ConvertPixelsToDp(float pixelValue)
        //{
        //    var dp = (int)((pixelValue) / Resources.DisplayMetrics.Density);
        //    return dp;
        //}

        bool isFirst = true;
        protected override void OnResume()
        {
            base.OnResume();
            if (isFirst)
            {
                isFirst = false;
                AppUnity.Instance.LogService.Log("UploadedView.OnResume First...");
                this.RefreshImg();
            }
            else
            {
                AppUnity.Instance.LogService.Log("UploadedView.OnResume More...");
                this.RefreshImg();
            }
        }
    }



}


